#!/usr/bin/python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""This code creates new companies from a text file"""

__author__ = 'felipel+bulk@google.com (Felipe Lora)'

# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import os
import sys
sys.path.insert(0, os.path.join('..', '..', '..', '..'))

# Import appropriate classes from the client library.
from adspygoogle.common import Utils
from adspygoogle.dfp.DfpClient import DfpClient
from adspygoogle.dfp import DfpUtils
from adspygoogle.dfp.DfpErrors import *

# Initialize client object.
client = DfpClient(path=os.path.join('..', '..', '..', '..'))

# Initialize appropriate service. By default, the request is always made against
# the production environment.
company_service = client.GetCompanyService('https://www.google.com', 'v201108')
label_service = client.GetLabelService('https://www.google.com', 'v201108')

# Global container of network's companies
networkCompanies = DfpUtils.GetAllEntitiesByStatementWithService(company_service)

# Gloabl container of network's labels
#networkLabels = DfpUtils.GetAllEntitiesByStatementWithService(label_service)

# Define names of logs
warningLog = "warnings_companies.log"
errorLog = "errors_companies.log"
successLog = "success_companies.log"

#############################################################

 
# Read all the advertisers to be created from the DoubleClick standard text file
def getFileCompanies(companyFile):
  global networkCompanies
  companies = []
  fcompanyFile = open(companyFile,'rU')

  name_indexer = dict((n['name'],i) for i,n in enumerate(networkCompanies))

  for line in fcompanyFile.readlines():
    validator = 1
    company = { 'name' : 0 }
    currLine = line.rsplit("^")
  
    companyName = currLine[0]
    companyType = currLine[1]
    companyExternalId = currLine[2]
    companyLabels = currLine[3].rsplit(',')

    if (len(companyName) < 128) and (companyName not in name_indexer) :
      company['name'] = companyName
    else :
      ferror = open(errorLog,'a')
      if len(companyName) > 127 :
        m = "%s, %s, The length of the name exceeds 127 characters\n" % (companyName, companyType.upper())
      else :
        m = "%s, %s, The company already exists in your network\n" % (companyName, companyType.upper())
      ferror.write(m)
      ferror.close()
      validator = 0
    
    if (companyType.upper() == "HOUSE_ADVERTISER") or (companyType.upper() == "HOUSE_AGENCY") or (companyType.upper() == "ADVERTISER") or (companyType.upper() == "AGENCY") or (companyType.upper() == "AD_NETWORK") :   
      company['type'] = companyType.upper()
    else :
      ferror = open(errorLog,'a')
      m = "%s, %s, The company type is not recognized\n" % (companyName, companyType.upper())
      ferror.write(m)
      ferror.close()
      validator = 0
  
    company['externalId'] = companyExternalId
    
    if len(companyLabels) > 1 :
      labels = []
      for label in companyLabels :
        labels.append(label.rstrip('\n'))
      company['labels'] = labels
    else : 
      company['labels'] = companyLabels[0].rstrip('\n')
    
    if validator == 1:
      companies.append(company)

  return companies

def createCompanies(companies):
  for c in companies:
    del c['labels']

  try:
    companies_created = company_service.CreateCompanies(companies)
    fs = open(successLog,'a')
    for c in companies_created:
      m = "%s,%s,%s\n" % (c['id'],c['name'],c['type'])
      fs.write(m)
    fs.close()
  except DfpRequestError,e:
    warningLogFile = open(warningLog,'a')
    message = "%s\n"  % (e.fault_string)
    warningLogFile.write(message)
    warningLogFile.close()

    return 1

def Main():
  # Clean old logs
  f = open(warningLog,'w')
  f.write("Company Name, Type, Message\n")
  f.close()
  f = open(errorLog,'w')
  f.write("Company Name, Type, Message\n")
  f.close()
  f = open(successLog,'w')
  f.write("ID, Company Name, Type, Labels\n")
  f.close()

  # Read the ad units from the text file
  args = sys.argv[1:]
  companyFile = args[0]
  companies = getFileCompanies(companyFile)
  # Create the advertisers
  createCompanies(companies)


if __name__ == '__main__':
  Main()
 

